package com.accloud.cloudservice;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.accloud.common.ACConfiguration;
import com.accloud.common.ACHelper;
import com.accloud.service.ACException;
import com.accloud.service.ClassData;
import com.accloud.service.Receiver;
import com.accloud.service.Topic;
import com.accloud.service.TopicData;
import com.accloud.utils.LogUtil;
import com.accloud.utils.PreferencesUtils;
import com.google.gson.Gson;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.java_websocket.client.DefaultSSLWebSocketClientFactory;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ServerHandshake;

public class ACSocketManager {
    private static final long BASE_RETRY_DELAY_MS = TimeUnit.SECONDS.toMillis(2);
    private static final String FRAME_HEARTBEAT = "heartbeat";
    private static final String FRAME_LOGIN = "loginWithSign";
    private static final String FRAME_SUBSCRIBE = "subscribe";
    private static final String FRAME_UNSUBSCRIBE = "unSubscribe";
    private static final long HEARTBEAT_PERIOD_MS = TimeUnit.MINUTES.toMillis(2);
    private static final long HEARTBEAT_TIMEOUT_MS = ((long) (((double) HEARTBEAT_PERIOD_MS) * 1.5d));
    private static final long MAX_RETRY_DELAY_MS = TimeUnit.SECONDS.toMillis(16);
    private static final int MSG_HEARTBEAT = 0;
    private static final int MSG_RECONNECT = 1;
    private static final int NO_ERROR = 0;
    private static final String TAG = "ACSocketManager";
    private Receiver<ClassData> mClassDataReceiver;
    private VoidCallback mConnectionCallback;
    private List<ConnectionListener> mConnectionListeners = new ArrayList();
    private Receiver<TopicData> mCustomDataReceiver;
    private Receiver<TopicData> mDeviceDataReceiver;
    private int mFrameSeqId = 0;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        /* class com.accloud.cloudservice.ACSocketManager.AnonymousClass1 */

        @Override // android.os.Handler
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (System.currentTimeMillis() - ACSocketManager.this.mLastHeartBeatResponse > ACSocketManager.HEARTBEAT_TIMEOUT_MS) {
                        ACSocketManager.this.reconnect();
                        return;
                    }
                    ACSocketManager.this.sendRequest(ACSocketManager.this.buildRequest(ACSocketManager.FRAME_HEARTBEAT, null, null, null));
                    ACSocketManager.this.mHandler.sendEmptyMessageDelayed(0, ACSocketManager.HEARTBEAT_PERIOD_MS);
                    return;
                case 1:
                    if (ACSocketManager.this.getState() == State.Disconnected) {
                        ACSocketManager.this.connectInternal();
                        return;
                    }
                    return;
                default:
                    return;
            }
        }
    };
    private long mLastHeartBeatResponse;
    private Map<Integer, SocketRequest> mPendingRequestQueue = new ConcurrentHashMap();
    private Map<Integer, SocketRequest> mRequestQueue = new ConcurrentHashMap();
    private long mRetryDelay = 0;
    private WebSocketClient mSocketClient;
    private State mState = State.Disconnected;

    /* access modifiers changed from: package-private */
    public interface ConnectionListener {
        void onLogin();
    }

    /* access modifiers changed from: private */
    public enum State {
        Connecting,
        Connected,
        Disconnected,
        Logined
    }

    private String getGatewayAddress() {
        return ACConfiguration.getAppGatewayAddr();
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private SocketRequest buildRequest(String api, String subDomain, Object payload, VoidCallback callback) {
        SocketRequest socketRequest = new SocketRequest(api);
        if (subDomain != null) {
            socketRequest.setSubDomain(subDomain);
        }
        socketRequest.setSignature(PreferencesUtils.getLong(AC.context, ACConfiguration.KEY_USERID, 0), new ACHelper().genSignature());
        socketRequest.setPayload(payload);
        socketRequest.setCallback(callback);
        return socketRequest;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void sendRequest(SocketRequest socketRequest) {
        int seqId = this.mFrameSeqId;
        this.mFrameSeqId = seqId + 1;
        socketRequest.setSeqId(seqId);
        this.mRequestQueue.put(Integer.valueOf(seqId), socketRequest);
        String msg = socketRequest.toJson();
        LogUtil.d(TAG, "send request: " + msg);
        this.mSocketClient.send(msg);
    }

    private SocketRequest pollRequest(int seqId) {
        SocketRequest socketRequest = this.mRequestQueue.get(Integer.valueOf(seqId));
        this.mRequestQueue.remove(Integer.valueOf(seqId));
        return socketRequest;
    }

    /* access modifiers changed from: package-private */
    public void tryConnect() {
        if (getState() == State.Disconnected) {
            connectInternal();
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void connectInternal() {
        if (setState(State.Connecting)) {
            LogUtil.d(TAG, "connect");
            resetConnection();
            try {
                this.mSocketClient = new WebSocketClient(new URI(getGatewayAddress()), new Draft_17()) {
                    /* class com.accloud.cloudservice.ACSocketManager.AnonymousClass2 */

                    @Override // org.java_websocket.client.WebSocketClient
                    public void onOpen(ServerHandshake handshakedata) {
                        LogUtil.d(ACSocketManager.TAG, toString());
                        LogUtil.d(ACSocketManager.TAG, "onOpen: " + handshakedata.getContent());
                        ACSocketManager.this.setState(State.Connected);
                        ACSocketManager.this.mRetryDelay = 0;
                        ACSocketManager.this.login();
                    }

                    @Override // org.java_websocket.client.WebSocketClient
                    public void onMessage(String message) {
                        LogUtil.d(ACSocketManager.TAG, toString());
                        LogUtil.d(ACSocketManager.TAG, "onMessage: " + message);
                        ACSocketManager.this.handleMessage(message);
                    }

                    @Override // org.java_websocket.client.WebSocketClient
                    public void onClose(int code, String reason, boolean remote) {
                        LogUtil.d(ACSocketManager.TAG, toString());
                        LogUtil.d(ACSocketManager.TAG, "onClose: code(" + code + ") reason(" + reason + ") remote(" + remote + ")");
                        if (code != 1000) {
                            ACSocketManager.this.setState(State.Disconnected);
                            ACSocketManager.this.reconnect();
                        }
                    }

                    @Override // org.java_websocket.client.WebSocketClient
                    public void onError(Exception ex) {
//                        int readyState = getReadyState();
//                        LogUtil.d(ACSocketManager.TAG, toString());
//                        LogUtil.d(ACSocketManager.TAG, "onError: readyState(" + readyState + ") exception(" + ex.getClass() + ") message(" + ex.getMessage() + ")");
//                        if (readyState == 0) {
//                            ACSocketManager.this.setState(State.Disconnected);
//                            ACSocketManager.this.reconnect();
//                        }
                    }
                };
                TrustManager[] trustAllCerts = {new X509TrustManager() {
                    /* class com.accloud.cloudservice.ACSocketManager.AnonymousClass3 */

                    @Override // javax.net.ssl.X509TrustManager
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }

                    @Override // javax.net.ssl.X509TrustManager
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override // javax.net.ssl.X509TrustManager
                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }
                }};
                SSLContext sc = null;
                try {
                    sc = SSLContext.getInstance("TLS");
                    sc.init(null, trustAllCerts, new SecureRandom());
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (KeyManagementException e2) {
                    e2.printStackTrace();
                }
                this.mSocketClient.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sc));
                this.mSocketClient.connect();
            } catch (URISyntaxException e3) {
                disconnect(e3);
            }
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void reconnect() {
        if (!this.mHandler.hasMessages(1)) {
            this.mHandler.sendEmptyMessageDelayed(1, this.mRetryDelay);
            if (this.mRetryDelay == 0) {
                this.mRetryDelay = BASE_RETRY_DELAY_MS;
            } else if (this.mRetryDelay < MAX_RETRY_DELAY_MS) {
                this.mRetryDelay *= 2;
            }
        }
    }

    private void resetConnection() {
        this.mHandler.removeMessages(0);
        if (this.mSocketClient != null) {
            this.mSocketClient.close();
        }
        this.mHandler.removeMessages(1);
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void handleMessage(String message) {
        final SocketMessage socketMessage = (SocketMessage) new Gson().fromJson(message,  SocketMessage.class);
        SocketRequest socketRequest = pollRequest(socketMessage.getSeqId());
        final BaseCallback callback = socketRequest != null ? socketRequest.getCallback() : null;
        String name = socketMessage.getName();
        final int errCode = socketMessage.getErrCode();
        LogUtil.d(TAG, "handleMessage: name(" + name + ") errCode(" + errCode + ") callback(" + callback + ")");
        char c = 65535;
        switch (name.hashCode()) {
            case -1868559828:
                if (name.equals(FRAME_LOGIN)) {
                    c = 0;
                    break;
                }
                break;
            case -1707717967:
                if (name.equals(FRAME_UNSUBSCRIBE)) {
                    c = 6;
                    break;
                }
                break;
            case -1582182725:
                if (name.equals(TopicData.FRAME_CUSTOM)) {
                    c = 4;
                    break;
                }
                break;
            case -10186430:
                if (name.equals(ClassData.FRAME_CLASS)) {
                    c = 2;
                    break;
                }
                break;
            case 200896764:
                if (name.equals(FRAME_HEARTBEAT)) {
                    c = 1;
                    break;
                }
                break;
            case 514841930:
                if (name.equals(FRAME_SUBSCRIBE)) {
                    c = 5;
                    break;
                }
                break;
            case 780691232:
                if (name.equals(TopicData.FRAME_DEVICE)) {
                    c = 3;
                    break;
                }
                break;
        }
        switch (c) {
            case 0:
                handleLogin(socketMessage, (VoidCallback) callback);
                return;
            case 1:
                handleHeartbeat(socketMessage);
                return;
            case 2:
                if (errCode == 0) {
                    final ClassData classData = (ClassData) new Gson().fromJson(socketMessage.getPayload(),  ClassData.class);
                    this.mHandler.post(new Runnable() {
                        /* class com.accloud.cloudservice.ACSocketManager.AnonymousClass4 */

                        @Override // java.lang.Runnable
                        public void run() {
                            if (ACSocketManager.this.mClassDataReceiver != null) {
                                ACSocketManager.this.mClassDataReceiver.onReceive(classData);
                            }
                        }
                    });
                    return;
                }
                return;
            case 3:
                if (errCode == 0) {
                    final TopicData topicData = (TopicData) new Gson().fromJson(socketMessage.getPayload(),  TopicData.class);
                    topicData.setSubDomain(socketMessage.getSubDomain());
                    this.mHandler.post(new Runnable() {
                        /* class com.accloud.cloudservice.ACSocketManager.AnonymousClass5 */

                        @Override // java.lang.Runnable
                        public void run() {
                            if (ACSocketManager.this.mDeviceDataReceiver != null) {
                                ACSocketManager.this.mDeviceDataReceiver.onReceive(topicData);
                            }
                        }
                    });
                    return;
                }
                return;
            case 4:
                if (socketMessage.getErrCode() == 0) {
                    final TopicData topicData2 = (TopicData) new Gson().fromJson(socketMessage.getPayload(),  TopicData.class);
                    topicData2.setSubDomain(socketMessage.getSubDomain());
                    this.mHandler.post(new Runnable() {
                        /* class com.accloud.cloudservice.ACSocketManager.AnonymousClass6 */

                        @Override // java.lang.Runnable
                        public void run() {
                            if (ACSocketManager.this.mCustomDataReceiver != null) {
                                ACSocketManager.this.mCustomDataReceiver.onReceive(topicData2);
                            }
                        }
                    });
                    return;
                }
                return;
            default:
                if (callback != null) {
                    this.mHandler.post(new Runnable() {
                        /* class com.accloud.cloudservice.ACSocketManager.AnonymousClass7 */

                        @Override // java.lang.Runnable
                        public void run() {
                            if (errCode != 0) {
                                callback.error(socketMessage.getError());
                            } else if (callback instanceof VoidCallback) {
                                ((VoidCallback) callback).success();
                            } else {
                                ((PayloadCallback) callback).success(null);
                            }
                        }
                    });
                    return;
                }
                return;
        }
    }

    private void handleHeartbeat(SocketMessage socketMessage) {
        if (socketMessage.getErrCode() == 0) {
            this.mLastHeartBeatResponse = System.currentTimeMillis();
        } else {
            reconnect();
        }
    }

    private void handleLogin(SocketMessage socketMessage, VoidCallback callback) {
        switch (socketMessage.getErrCode()) {
            case 0:
                setState(State.Logined);
                if (callback != null) {
                    callback.success();
                }
                this.mLastHeartBeatResponse = System.currentTimeMillis();
                this.mHandler.sendEmptyMessageDelayed(0, HEARTBEAT_PERIOD_MS);
                for (SocketRequest socketRequest : this.mPendingRequestQueue.values()) {
                    sendRequest(socketRequest);
                }
                this.mPendingRequestQueue.clear();
                for (ConnectionListener listener : this.mConnectionListeners) {
                    listener.onLogin();
                }
                return;
            case 3515:
                try {
                    LogUtil.d(TAG, "updateAccessToken");
                    AC.accountMgr().updateAccessToken();
                    return;
                } catch (ACException e) {
                    disconnect(e);
                    return;
                }
            default:
                disconnect(socketMessage.getError());
                return;
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void login() {
        if (getState() == State.Connected) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("keepAlive", Long.valueOf(TimeUnit.MILLISECONDS.toSeconds(HEARTBEAT_PERIOD_MS)));
            sendRequest(buildRequest(FRAME_LOGIN, null, map, null));
        }
    }

    private void disconnect(Exception e) {
        String detail;
        if (setState(State.Disconnected)) {
            if (e == null) {
                detail = "exception(null)";
            } else {
                detail = "exception(" + e.getClass() + ") message(" + e.getMessage() + ")";
            }
            LogUtil.d(TAG, "disconnect " + detail);
            this.mRetryDelay = 0;
            resetConnection();
            if (!(this.mConnectionCallback == null || e == null)) {
                this.mConnectionCallback.error(e instanceof ACException ? (ACException) e : new ACException(ACException.INTERNAL_ERROR, e));
            }
            this.mConnectionCallback = null;
        }
    }

    /* access modifiers changed from: package-private */
    public void setClassDataReceiver(Receiver<ClassData> receiver) {
        this.mClassDataReceiver = receiver;
    }

    /* access modifiers changed from: package-private */
    public void setDeviceDataReceiver(Receiver<TopicData> receiver) {
        this.mDeviceDataReceiver = receiver;
    }

    /* access modifiers changed from: package-private */
    public void setCustomDataReceiver(Receiver<TopicData> receiver) {
        this.mCustomDataReceiver = receiver;
    }

    /* access modifiers changed from: package-private */
    public void subscribe(Topic topic, VoidCallback callback) {
        SocketRequest socketRequest = buildRequest(FRAME_SUBSCRIBE, topic.subDomain, topic, callback);
        if (getState() != State.Logined) {
            this.mPendingRequestQueue.put(Integer.valueOf(this.mPendingRequestQueue.size()), socketRequest);
        } else {
            sendRequest(socketRequest);
        }
    }

    /* access modifiers changed from: package-private */
    public void unSubscribe(Topic topic, VoidCallback callback) {
        sendRequest(buildRequest(FRAME_UNSUBSCRIBE, topic.subDomain, topic, callback));
    }

    /* access modifiers changed from: package-private */
    public boolean isLogined() {
        return getState() == State.Logined;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private synchronized boolean setState(State state) {
        boolean changed;
        changed = this.mState != state;
        this.mState = state;
        return changed;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private synchronized State getState() {
        return this.mState;
    }

    /* access modifiers changed from: package-private */
    public void addConnectionListener(ConnectionListener listener) {
        this.mConnectionListeners.add(listener);
    }
}
